package com.whj.servicemap.remote;

import com.whj.internalcommon.constant.AMapConfigConstant;
import com.whj.internalcommon.dto.ResponseResult;
import com.whj.internalcommon.response.ServiceResponse;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @Auther: wanghaijun
 * @Date: 2023/1/16 - 01 - 16 - 14:13 
 * @Description: com.whj.servicemap.remote
 */

@Service
@Slf4j
public class ServiceClient {


    @Value("${amap.key}")
    private String amapKey;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 根据传来的名称在高德创建对应的服务
     * @param name
     * @return
     */
    public ResponseResult add(String name) {

        StringBuilder url = new StringBuilder();
        url.append(AMapConfigConstant.SERVICE_ADD_URL);
        url.append("?");
        url.append("key=" + amapKey);
        url.append("&");
        url.append("name=" + name);
        log.info(url.toString());

        ResponseEntity<String> forEntity = restTemplate.postForEntity(url.toString(), null, String.class);

        /**
         * # 服务创建 解析数据
         * {
         *     "data": {
         *         "name": "飞滴出行Service",
         *         "sid": 869338
         *     },
         *     "errcode": 10000,
         *     "errdetail": null,
         *     "errmsg": "OK"
         * }
         */
        String body = forEntity.getBody();
        JSONObject result = JSONObject.fromObject(body);
        JSONObject data = result.getJSONObject("data");
        String sid = data.getString("sid");
        ServiceResponse serviceResponse = new ServiceResponse();
        serviceResponse.setSid(sid);
        return ResponseResult.success(serviceResponse);
    }
}
